package com.huluobo.lib_base

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.huluobo.lib_base.entity.LocalEntity
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.receiveAsFlow
import kotlinx.coroutines.launch
import okhttp3.Request
import java.io.File
import java.lang.Exception

/**
 *  Created by LC on 2025/2/5.
 */
abstract class BaseViewModel<uiIntent : UIIntent> : ViewModel() {

    private val _uiIntent = Channel<UIIntent>(Channel.UNLIMITED)

    private var _state = MutableStateFlow<UIState>(UIState.onLoading)
    val state: StateFlow<UIState>
        get() = _state

    init {
        viewModelScope.launch {
            _uiIntent.receiveAsFlow().collect {
                handleIntent(it)
            }
        }
    }

    abstract fun handleIntent(it: UIIntent)

    fun sendIntent(intent: UIIntent) {
        viewModelScope.launch {
            _uiIntent.send(intent)
        }
    }

    fun httpRequest(request: Flow<Res<Any>>, type: HttpType = HttpType.DEFAULT) {
        viewModelScope.launch {
            request.flowOn(Dispatchers.IO)
                .catch {
                    Log.e("TagA", "error:${it.message}")
                }.collect {
                    if (it.code == 0) {
                        _state.value = UIState.onSuccess(it.data, type)
                    } else {
                        _state.value = UIState.onError(it.msg)
                    }
                }
        }
    }

    fun download(url: String, file: File) {
        viewModelScope.launch {
            DownloadUtil.download(url, file)
                .flowOn(Dispatchers.IO)
                .catch {
                    Log.e("TagA", "downError:${it.message}")
                }.collect {
                    _state.value = it
                }
        }
    }

    fun scanFile(file: File) {
        viewModelScope.launch {
            try {
                val files = file.listFiles()
                val list = mutableListOf<LocalEntity>()
                for (it in files) {
                    list.add(LocalEntity(it.name, it.absolutePath))
                }
                _state.value = UIState.onSuccess(list)
            } catch (e: Exception) {
                _state.value = UIState.onError(e.message.toString())
            }
        }
    }

    fun roomRequest(request: Flow<Any>, type: HttpType = HttpType.DEFAULT) {
        viewModelScope.launch {
            request.flowOn(Dispatchers.IO)
                .catch {
                    Log.e("TagA", "数据库错误:${it.message.toString()}")
                }.collect {
                    if (it != null) {
                        _state.value = UIState.onSuccess(it, type)
                    } else {
                        _state.value = UIState.onError("数据库操作错误")
                    }
                }
        }
    }
}